package com.zuohuaipan.headine.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.zuohuaipan.headine.R;
import com.zuohuaipan.headine.adapter.XList_adapter;
import com.zuohuaipan.headine.bean.NewsSummary;
import com.zuohuaipan.headine.view.WebActivity;
import com.zuohuaipan.lazyviewpager_master.LazyFragmentPagerAdapter;
import com.zuohuaipan.xlistview.XListView;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
import java.util.Map;

public class NewsFragment extends Fragment implements LazyFragmentPagerAdapter.Laziable, XListView.IXListViewListener {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private XListView xlv;
    int count = 0;
    /**
     * 判断是否初始化
     */
    private boolean injected = false;
    private Callback.Cancelable cancelable;
    private ArrayList<NewsSummary> arrayList;
    private XList_adapter adapter;

    public NewsFragment() {
        // Required empty public constructor
    }


    // TODO: Rename and change types and number of parameters
    public static NewsFragment newInstance(String param1, String param2) {
        NewsFragment fragment = new NewsFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        injected = true;
        View view = inflater.inflate(R.layout.fragment_news, container, false);
        //初始化控件
        initView(view);
        arrayList = new ArrayList<>();
        return view;

    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        //判断有没有初始化
        if (!injected) {//没有初始化回调getview方法
            x.view().inject(this, getView());
        }
        //下拉刷新
        onRefresh();
        //监听
        setxlvListener();
        //跳转
        lookNews();

    }

    /**
     * 跳转
     */
    private void lookNews() {
        xlv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(getActivity(), WebActivity.class);
                String url_3w = arrayList.get(position - 1).url_3w;
                if (url_3w != null) {
                    intent.putExtra("newsurl", url_3w);
                    startActivity(intent);
                }


            }
        });
    }

    public void setxlvListener() {
        xlv.setPullRefreshEnable(true);
        xlv.setPullLoadEnable(true);
        xlv.setXListViewListener(this);
    }

    /**
     * 初始化url
     *
     * @param type
     * @param typeid
     * @param index
     */

    private RequestParams geturl(String type, String typeid, int index) {
        String url = String.format("http://c.m.163.com/nc/article/%1$s/%2$s/%3$s-20.html", type, typeid, index);

        return new RequestParams(url);
    }

    /**
     * 请求网络
     */
    private void getNewList(String type, final String typeid, int index) {
        //初始化url
        RequestParams params = geturl(type, typeid, index);

        //请求成功
        cancelable = x.http().get(params, new Callback.CommonCallback<String>() {
            //请求成功
            @Override
            public void onSuccess(String result) {
                //解析数据
                arrayList.addAll(parseData(result, typeid));


            }

            //            网络请求错误
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            //          网络请求取消
            @Override
            public void onCancelled(CancelledException cex) {

            }

            //          更新UI
            @Override
            public void onFinished() {
                updateUI(arrayList);
                xlv.stopLoadMore();
            }
        });

    }

    /**
     * 更新适配器
     *
     * @param arrayList
     */
    private void updateUI(ArrayList<NewsSummary> arrayList) {
        if (count == 0) {
            adapter = new XList_adapter(getActivity(), arrayList);
            xlv.setAdapter(adapter);
        } else {
            //XList_adapter xList_adapter = new XList_adapter(getActivity(), arrayList);
            adapter.notifyDataSetChanged();
        }


    }

    /**
     * 解析数据
     *
     * @param result
     * @param typeid
     */
    private ArrayList<NewsSummary> parseData(String result, String typeid) {
        Map<String, ArrayList<NewsSummary>> map = new Gson().fromJson(result, new TypeToken<Map<String, ArrayList<NewsSummary>>>() {
        }.getType());
        ArrayList<NewsSummary> list = map.get(typeid);

        return list;
    }


    private void initView(View view) {
        xlv = (XListView) view.findViewById(R.id.xlv);
    }

    /**
     * 下拉刷新
     */
    @Override
    public void onRefresh() {
        count = 0;
        arrayList.clear();
        //请求数据
        getNewList(mParam1, mParam2, count);
        //上次刷新时间
        xlv.setRefreshTime(getTime());
        //关闭
        xlv.stopRefresh();

    }

    /**
     * 上拉加载
     */
    @Override
    public void onLoadMore() {
        count = count + 20;
        //请求数据
        getNewList(mParam1, mParam2, count);
        //关闭


        Log.d("zzz", "000000000000000000000000000000000");
    }

    /**
     * 计算时间
     *
     * @return
     */
    private String getTime() {
        return new SimpleDateFormat("MM-dd HH:mm", Locale.CHINA).format(new Date());
    }

    @Override
    public void onPause() {
        super.onPause();
        if (cancelable != null) {//取消请求
            cancelable.cancel();
        }
    }
}
